package com.battery.eason.controller;

import com.battery.eason.pojo.RespBean;
import com.battery.eason.service.BasicService;
import com.battery.eason.utils.QRCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 基本接口控制器
 *
 * @author HuangSiYuan
 * @since 2021-08-21
 */
@RestController
public class BasicController {

    @Autowired
    private BasicService basicService;

    @Value("${upload.baseUrl}")
    private String baseUrl;



    @ApiOperation("图片上传接口")
    @PostMapping("/upload")
    public RespBean upload(MultipartFile file) throws IOException {
        return basicService.uploadFile(file);
    }


    @ApiOperation("获取图片流")
    @GetMapping("/getImgStream")
    public void getImgStream(@RequestParam("imgPath") String imgPath, HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        try {
//            File file = new File("/data/share_battery/upload" + File.separator+ imgPath);
//            File file = new File("S:\\imgFile" + File.separator+ imgPath);
            File file = new File(baseUrl + File.separator+ imgPath);
            response.setContentType("image/"+imgPath.split("\\.")[1]);
            OutputStream out = response.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            response.getWriter().write("文件不存在");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    System.out.println("关闭流失败!");
                }
            }
        }
    }

    /**
     * 根据 content 生成二维码
     *
     * @param content
     * @param width
     * @param height
     * @return
     */
    @GetMapping("/getQRCodeBase64")
    public RespBean getQRCode(@RequestParam("content") String content,
                       @RequestParam(value = "logoUrl", required = false) String logoUrl,
                       @RequestParam(value = "width", required = false) Integer width,
                       @RequestParam(value = "height", required = false) Integer height) {
        return RespBean.success(QRCodeUtil.getBase64QRCode(content, logoUrl));
    }


}
